const Api = require('../model/ApiModel')
const { list2tree } = require('../utils/utils')
const mongoose = require('mongoose')
const { ObjectId } = mongoose.Types
exports.list = async (req, res) => {
  const apis = await Api.find().lean()
  res.json({
    code: 20000,
    message: '查询所有api成功',
    data: {
      items: apis,
      total: apis.length
    }
  })
}

exports.tree = async (req, res) => {
  const condition = {}
  let { q } = req.query
  if (q) {
    q = q.trim().toUpperCase()
    if (q === 'GROUP') {
      condition.type = 'GROUP'
    }
  }

  const menuTree = await Api.find(condition).lean()
  const { treeData, objData } = list2tree(menuTree, null)
  res.json({
    code: 20000,
    message: '获取api树状结构成功',
    data: {
      items: treeData,
      total: treeData.length,
      objData
    }
  })
}

exports.create = async (req, res) => {
  const data = req.body
  delete data._id
  if (data.type && data.type === 'GROUP') {
    delete data.method
    delete data.path
  }
  if (!ObjectId.isValid(data.parent)) {
    delete data.parent
  }
  console.log('🚀 ~ file: api.controller.js ~ line 49 ~ exports.create= ~ data', data)
  const result = await Api.create(data)
  const count = await Api.countDocuments()
  res.json({
    code: 20000,
    message: '创建api成功',
    data: result,
    count
  })
}

exports.realRemove = async (req, res) => {
  const id = req.params.id
  await Api.findByIdAndRemove(id)
  res.json({
    code: 20000,
    message: 'api删除成功'
  })
}

exports.update = async (req, res) => {
  const id = req.params.id
  const data = req.body
  delete data._id
  if (data.type && data.type === 'GROUP') {
    delete data.method
    delete data.path
  }
  if (!ObjectId.isValid(data.parent)) {
    delete data.parent
  }
  const result = await Api.findByIdAndUpdate(id, data, { new: true })
  res.json({
    code: 20000,
    message: '更新api成功',
    data: result
  })
}
